package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.RedisService.IUserInfoRedisService;
import cn.wolfcode.luowowo.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * 用户登录
 *
 * */
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    //登录拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断handler是否是HandlerMethod的实例
        //可以解决跨越拦截跟静态请求拦截
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //1.识别请求映射方法是否贴有注解
        //获取令牌
        String token = request.getHeader("token");
        //根据令牌查缓存数据库，判断是否已经登录
        //重置30分钟
        UserInfo user = userInfoRedisService.getUserByToken(token);
        HandlerMethod hm = (HandlerMethod) handler;
        if (hm.hasMethodAnnotation(RequireLogin.class)) {
            //如果贴了需要登录效验
            //如果没有登录
            if (user == null) {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        //如果没贴直接放行
        return true;
    }
}
